﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Specialized;

namespace Aliyun.Oss
{
	public static class Extensions
	{
		public static NameValueCollection NameValue(this Object obj)
		{
			var c = new NameValueCollection();

			foreach (var p in obj.GetType().GetProperties())
			{
				c.Add(p.Name, p.GetValue(obj, null).ToString());
			}

			return c;
		}

		public static string DefaultOrEmpty(this NameValueCollection collection, string key)
		{
			if (collection.AllKeys.Contains(key))
				return collection[key];

			return "";
		}

		/// <summary>
		/// ordered by key
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="fmt"></param>
		/// <returns></returns>
		public static string KeyValue(this NameValueCollection collection,string fmt = "{0}:{1}\n")
		{
			StringBuilder sb = new StringBuilder();
			foreach (string key in collection.AllKeys.OrderBy(k=>k))
			{
				sb.AppendFormat(fmt, key, collection[key]);
			}
			return sb.ToString();
		}

		public static byte[] SHA1(this String text, string salt)
		{
			var hmac = new HMACSHA1(System.Text.UTF8Encoding.UTF8.GetBytes(salt.ToCharArray()));
			byte[] hash = hmac.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(text.ToCharArray()));
			hmac.Clear();

			return hash;
		}

		public static string JoinWith(this IList<string> items, string c)
		{
			int i = 0;
			StringBuilder sb = new StringBuilder();

			for (; i < items.Count() - 1; i++)
			{
				sb.Append(items[i] + c);
			}

			sb.Append(items[i]);

			return sb.ToString();
		}
	}
}
